#include "../master.h"
#include <wininet.h>
#include <commctrl.h>
#include "../comfunct/comfunct.h"
#include "resource.h"

extern HWND hUpdateBox;
extern HFONT hfBold, hfDefault;
extern bool bStop;

bool DownloadPlayerUpdate()
{     
	LPCTSTR szFilterTypes[] = {TEXT("*/*"), NULL};
    HINTERNET hInitConnect = NULL, hHostConnect = NULL, hRequestParams = NULL;
	BOOL bWriteSuccess = FALSE, bSent = FALSE;
    DWORD dwRemoteFileSize = 0, dwBytesDownloaded = 1, dwCount = 0, dwBytesWritten = 0, dwDataAvailable = 0;
    DWORD dwSize = sizeof(dwRemoteFileSize), dwDownloadedSize = 0;
    HANDLE hUpdatePack = NULL;
    TCHAR szFilePath[MAX_PATH] = TEXT("");
    OSVERSIONINFO osVer = {0};
	bool bFinished = false;
	char* szLang = NULL;
	TCHAR* szExt = TEXT(".exe");
     
    if(MessageBox(hUpdateBox, GetLocalText(88), TEXT("AudioPlayer"), MB_YESNO | MB_ICONINFORMATION | MB_DEFBUTTON1) == IDNO)
    {
        return false;
    }
     
    hInitConnect = ConnectHandle(TEXT("AudioPlayer"));
    hHostConnect = ServerConnect(hInitConnect, TEXT("kent.dl.sourceforge.net"));
     
    osVer.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
    GetVersionEx(&osVer);

	szLang = GetCurrentLanguage();

	_tcscpy(szFilePath, TEXT("/sourceforge/audioplayer/AudioPlayer_1.0_"));

	if(strcmp(szLang, "eng") == 0)
	{
		if(osVer.dwPlatformId == VER_PLATFORM_WIN32_WINDOWS) /* If we're on Win98 or ME download the 98ME version */
		{
			_tcscat(szFilePath, TEXT("98ME"));
		}
		else 
		{
			_tcscat(szFilePath, TEXT("NTXP"));
	    }
		_tcscat(szFilePath, szExt);
	}
	else
	{
		WCHAR* szWideLang = NULL;
		_tcscat(szFilePath, TEXT("NTXP_"));

#ifdef UNICODE

		szWideLang = UnicodeConversion(szLang);
		wcscat(szFilePath, szWideLang);
		FreePointer(szWideLang);

#else

		strcat(szFilePath, szLang);

#endif

		_tcscat(szFilePath, szExt);
	}

	FreePointer(szLang);
     
    SendDlgItemMessage(hUpdateBox, DLG_PROGRESS, PBM_SETPOS, 0, 0);
    SendDlgItemMessage(hUpdateBox, DLG_STEP2, WM_SETFONT, (WPARAM)hfDefault, MAKELPARAM(TRUE, 0)); /* Set the second step text back to normal */
    SendDlgItemMessage(hUpdateBox, DLG_STEP3, WM_SETFONT, (WPARAM)hfBold, MAKELPARAM(TRUE, 0)); /* and bolden the third step since that's where we are */
     
    hRequestParams = HttpOpenRequest(hHostConnect, TEXT("GET"), szFilePath,
                               NULL, NULL, szFilterTypes, INTERNET_FLAG_NO_COOKIES | INTERNET_FLAG_RELOAD | INTERNET_FLAG_PRAGMA_NOCACHE, 0);
    if(hRequestParams == NULL)
    {
        ErrorInfo();
        ErrorMessage(GetLocalText(89));
		InternetCloseHandle(hHostConnect);
		InternetCloseHandle(hInitConnect);
        return false;
    }
     
    bSent = HttpSendRequest(hRequestParams, NULL, 0L, NULL, 0);
    if(bSent == FALSE)
    {
        ErrorInfo();
        ErrorMessage(GetLocalText(90));
		InternetCloseHandle(hRequestParams);
		InternetCloseHandle(hHostConnect);
		InternetCloseHandle(hInitConnect);
        return false;
    }

    /* Find out how big the file is */ 
    HttpQueryInfo(hRequestParams, HTTP_QUERY_CONTENT_LENGTH | HTTP_QUERY_FLAG_NUMBER, (LPVOID)&dwRemoteFileSize, &dwSize, NULL);
	/* And make the progress bar that long */
    SendDlgItemMessage(hUpdateBox, DLG_PROGRESS, PBM_SETRANGE32, 0, dwRemoteFileSize);
     
    hUpdatePack = CreateFile(TEXT("audioplayer_setup.exe"), GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE,
                             NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
         
    if(hUpdatePack == NULL || hUpdatePack == INVALID_HANDLE_VALUE)
    {
        ErrorInfo();
        ErrorMessage(GetLocalText(91));
		InternetCloseHandle(hRequestParams);
		InternetCloseHandle(hHostConnect);
		InternetCloseHandle(hInitConnect);
        return false;
    }
     
    do
	{         
        char* szUpdateFile = NULL;

	    if(bStop == true) /* If the Stop button has been pressed */
        {
            DeleteFile(TEXT("audioplayer_setup.exe"));
            CloseHandle(hUpdatePack);
			InternetCloseHandle(hRequestParams);
			InternetCloseHandle(hHostConnect);
			InternetCloseHandle(hInitConnect);
            return false;
        }
         
        InternetQueryDataAvailable(hRequestParams, &dwDataAvailable, 0, 0); /* See how much of the file we can download this time round the loop */
		
		if(dwDataAvailable == 0) /* If there is no more data to get, we've finished */
        {
			bFinished = true;
			break;
        }
         
        szUpdateFile = malloc(dwDataAvailable); /*  */
         
        dwBytesDownloaded = 1;
        dwCount = 0;
    
        while(dwBytesDownloaded != 0) /* dwBytedDownloaded is set to 0 when InternetReadFile has read all available data into the buffer */
        {
            if(!InternetReadFile(hRequestParams, &szUpdateFile[dwCount], dwDataAvailable - dwCount, &dwBytesDownloaded))
            {
                ErrorInfo();
                ErrorMessage(TEXT("InternetReadFile failed"));
				InternetCloseHandle(hRequestParams);
				InternetCloseHandle(hHostConnect);
				InternetCloseHandle(hInitConnect);
                return false;
            }
            dwCount += dwBytesDownloaded;
        }
        SetEndOfFile(hUpdatePack); /* Move the file pointer to the end of the file so we can append the downloaded data */
        bWriteSuccess = FALSE;
        bWriteSuccess = WriteFile(hUpdatePack, szUpdateFile, dwDataAvailable, &dwBytesWritten, NULL);
        if(bWriteSuccess == FALSE)
        {
            ErrorInfo();
            ErrorMessage(GetLocalText(87));
			InternetCloseHandle(hRequestParams);
			InternetCloseHandle(hHostConnect);
			InternetCloseHandle(hInitConnect);
            return false;
        }
        free(szUpdateFile);
        dwDownloadedSize = GetFileSize(hUpdatePack, NULL); /* See how much we've downloaded and use it to update the progress bar */
        SendDlgItemMessage(hUpdateBox, DLG_PROGRESS, PBM_SETPOS, dwDownloadedSize, 0);
     } while(bFinished != true);
     
    CloseHandle(hUpdatePack);
    return true;
}
